package com.yc.thread;

import java.util.Random;

public class SynDemo {

    static int i = 0;

    public static void main(String[] args) throws InterruptedException {
        for (int j = 0; j < 10; j++) {
            new Thread( ()->{
                for (int k = 0; k < 10000; k++) {
                    // 同步代码块
//                    synchronized (SynDemo.class){
//                        // 非原子操作
//                        i++;
//                    }
                    addi();
                }
            } ).start();
        }

        Thread.sleep(2000);

        System.out.println("i = " + i);

        System.out.println("--------------------------------");

        SynDemo sd = new SynDemo();

        Thread t1 = new Thread(()->{
            sd.add();
        });
        Thread t2 = new Thread(()->{
            sd.sub();
        });
        Thread t3 = new Thread(()->{
            sd.show();
        });

        t1.start();
        t2.start();
        t3.start();
    }

    // 同步方法： 静态方法锁定的是当前 类 SynDemo.class
    public synchronized static void addi(){
        i++;
    }


    int j=0;

    // 实例同步方法 锁定的对象时当前对象  this
    public synchronized void add(){
        System.out.println(" begin add");
        try {
            Thread.sleep(new Random().nextInt(1000));
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        j++;
        System.out.println(" end add");
    }

    public synchronized void sub(){
        System.out.println(" begin sub");
        try {
            Thread.sleep(new Random().nextInt(1000));
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        j--;
        System.out.println(" end sub");
    }

    public void show(){
        System.out.println("j = " + j);
    }



}
